#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import grp
import pwd

from common.common_models import QueryPermissionModel
from generaldb.gbase8a import LOGGER
from generaldb.gbase8a.commands.gbase_cmd import GbaseCmd
from generaldb.gbase8a.common.const import EnvName, AllStepEnum
from generaldb.gbase8a.job_manager import JobManager
from generaldb.gbase8a.service.base_service import MetaService


class JobPermission(MetaService):
    def __init__(self, job_manager, param_dict):
        super().__init__(job_manager, param_dict)
        EnvName.DB_USER_NAME = "appEnv_auth_authKey"
        EnvName.DB_PASSWORD = "appEnv_auth_authPwd"
        EnvName.CUSTOM_SETTINGS = "appEnv_auth_extendInfo_authCustomParams"
        self.cmd = GbaseCmd(job_manager.pid)

    def query_job_permission(self):
        os_user = self.cmd.get_os_user()
        LOGGER.info(os_user)
        if not os_user:
            return
        group_id = pwd.getpwnam(str(os_user)).pw_gid
        group_name = grp.getgrgid(group_id).gr_name
        permission = QueryPermissionModel(
            user=os_user,
            group=group_name,
            fileMode='0755'
        )
        self.job_manager.update(permission.dict(by_alias=True))

    def gen_param_obj(self):
        pass

    def get_steps(self):
        pass


@JobManager.register(AllStepEnum.QUERY_JOB_PERMISSION)
class QueryJobPermission(JobPermission):
    def __init__(self, job_manager, param_dict):
        super().__init__(job_manager, param_dict)
        self.need_report = False

    def get_steps(self):
        steps = [self.query_job_permission]
        return steps

    def gen_param_obj(self):
        pass
